<template>
  <!-- <h2>物品管理</h2> -->
    <div class="goods-main" v-loading="loading">

      <div class="goods-head">
        <el-button class="btn-2" @click="handleRefresh" >刷新</el-button>
        <el-button class="btn-2" @click="handleCancelGood" >取消选中物品</el-button>
        <el-button class="btn-2" @click="handleClickDrawer" v-jurisdiction="'warehouse:good:createGood'">新建物品</el-button>
      </div>
      <div class="goods-content">
        <div class="left-area">
          <div class="area-search">
            <el-input
              v-jurisdiction="'warehouse:good:getGoodList'"
              placeholder="物品名称/常用名"
              class="input-6"
              v-model="name"
              @keyup.enter="onSubmit"
              >
              <template #prefix>
                <el-icon><search /></el-icon>
              </template>
            </el-input>
          </div>
          <div class="area-tree" ref="areaTreeRef">
            <div class="all-goods">全部物品</div>
            <!-- <ztree :treeData="treeData" :defaultProps="defaultProps" @handleNode="handleNode"></ztree> -->
            <el-tree
              default-expand-all
              :props="defaultProps"
              :data="treeData"
              :load="loadNode"
              @node-click="handleNode"
              @node-contextmenu="handleNodeMenu"
              >
                
            </el-tree>
          </div>
          <div class="area-btn-operation" v-jurisdiction="'warehouse:good:type:add'">
            <span @click="addGoodType">
              <el-icon><plus /></el-icon>
              <span>添加物品类型</span>
            </span>
          </div>
        </div>
        <div class="right-area">
          <div class="table">
            <ztable 
              :tableData='data' 
              :strucs='groupData'
              :header-cell-style="{background:'#11b9d0', color:'#fff'}"
              :height="'100%'"
              :isshowOperation="true"
            >
            <template #default="slotScope">
              <el-button type="text" class="operation" @click="handleEditItem(slotScope.rowData)" v-jurisdiction="'warehouse:good:updateGood'">修改</el-button>
              <!-- <el-button type="text" class="operation" @click="handleWarning(slotScope.rowData)" v-jurisdiction="'warehouse:plOrder:orderDetail'">预警</el-button> -->
              <el-button type="text" class="operation" @click="handleDelItem(slotScope.rowData)" v-jurisdiction="'warehouse:good:del'">删除</el-button>
            </template>
            </ztable>
          </div>
          <div class="page">
              <zpage 
                :currentPage="current" 
                :total="total" 
                :pageSize="size"
                @handleSizeChange="handleSizeChange" 
                @handleCurrentChange="handleCurrentChange"
            ></zpage>
          </div>
        </div>
      </div>
    
    </div>

    <!-- 右击提示操作框 -->
    <div class="tipsOperation" ref="tipsOPerRef" v-show="menuVisbile">
      <div class="tip-item" @click="edit" v-jurisdiction="'warehouse:good:type:update'">
        <el-icon><edit /></el-icon>
        <span>修改</span>
      </div>
      <div class="tip-item" @click="remove" v-jurisdiction="'warehouse:good:type:del'">
        <el-icon><delete /></el-icon>
        <span>删除</span>
      </div>
    </div>

      <zdrawer size="40%" @handleClose="drawerClose('add')" title="新建物品" v-model="showDrawer" >
      <template #body>
      <!-- 动态 -->
      <ztitleBorder title="基础信息">
        <div class="dynamic flex-wrap">
          <component :is="showWidget(item.type)" class="test" v-for="item in groupDataAdd" :key="item.name" :struc="item" :passWidth="50"  />
        </div>
      </ztitleBorder>
      </template>
      <template #footer>
        <el-button class="btn-2" @click="cancel('add')">取消</el-button>
        <el-button class="btn-1" @click="save('add')">保存资料</el-button>
      </template>
    </zdrawer>
    <!-- 修改 -->
    <zdrawer size="40%" @handleClose="drawerClose('edit')" title="修改物品" v-model="showEditDrawer" >
      <template #body>
      <!-- 动态 -->
      <ztitleBorder title="基础信息">
        <div class="dynamic flex-wrap">
          <component :is="showWidget(item.type)" class="test" v-for="item in groupDataUpdate" :key="item.name" :struc="item" :passWidth="50"  />
        </div>
      </ztitleBorder>
      </template>
      <template #footer>
        <el-button class="btn-2" @click="cancel('edit')">取消</el-button>
        <el-button class="btn-1" @click="save('edit')">保存资料</el-button>
      </template>
    </zdrawer>

    <!-- 添加物品类型 -->
    <zdialog :title="titleType" @handleClose="closeDialog" v-model="dialogVisible" :btnData="dialogBtnData">
      <template #body>
        <div class="flex-wrap">
          <div class="leftToRight-layout" style="width: 100%">
            <div class="label">
              <span>类型名称</span>
            </div>
            <div class="operations">
              <el-input  v-model="nameType" ></el-input>
            </div>
          </div>
          <div class="leftToRight-layout" style="width: 100%" v-show="typeId === ''">
            <div class="label">
              <span>分类类型</span>
            </div>
            <div class="operations">
              <el-select v-model="itemType"  placeholder="请选择" clearable>
              <el-option
                v-for="item in modelOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
            </div>
          </div>
        </div>
        
      </template>
  </zdialog>
</template>

<script lang='ts'>
import { Plus, Delete, Edit, Search } from '@element-plus/icons-vue'
import { defineComponent, reactive, ref, toRefs, watch } from '@vue/runtime-core'
import ztable from '@components/Table/index.vue'
import zpage from '@components/pagination/pagination.vue'
import zsearch from '@components/search/search.vue'
import zdrawer from "@components/drawer/drawer.vue";
import ztitleBorder from "../../components/titleBorder/titleBorder.vue"
import ztree, {NodeChildren} from "../../components/tree/tree.vue"
import zdialog from '@components/dialog/dialog.vue'

import useShowWidget from "../../components/widget/usechoose";

import useConfgin from '../../hook/getconfig'
import useUser from "../../hook/user";
import useRequet, { RespData } from "../../hook/network"
import { DataStruc } from "../../hook/datastruc";
import {Option} from "../../types/index"


import { useRouter } from "vue-router"
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'

const ID = 512;
export default defineComponent({
  name: 'Goods',
  components: {
    ztable,
    zpage,
    zsearch,
    zdrawer,
    ztitleBorder,
    ztree,
    zdialog,

    Plus, Delete, Edit, Search

  },
  setup() {
    const router = useRouter();
    const request = useRequet({ path: "" });
    const {groupData, groupDataAdd, groupDataUpdate} = useConfgin(ID)
     /** 列表部分 -> 开始 */
    let search = reactive({
      date:'',
      current: 1,
      size: 10,
      total: 0,
      id: null,
      loading: false,
      name: ''
    })
    const data = ref([])
    const AddList = ref([] as DataStruc[])
    console.log(groupData, groupDataAdd, groupDataUpdate)

    //搜索
    const hanledSearch = () => {
      req()
    }
    // 分页
    const handleCurrentChange = (val: number) => {
			search.current = val
      req()
			console.log('handleCurrentChange', val)
		}
    const handleSizeChange = (val: number) => {
      search.size = val
      req()
			console.log('handleSizeChange', val)
		}


    const handleCancelGood = () => {
      tree.typeId = ''
      req()
    }

    const handleRefresh = () => {
      req()
    }


    const onSubmit = () => {
      req()
      console.log('onSubmit')
    }

    /** 列表部分 -> 结束 */

    /** 物品分类树 */
    const tree = reactive({
      treeData: [],
      typeId: '',
    })

    const req = () => {
      search.loading = true;
      let params = {
        name: search.name || '',
        current: search.current,
        size: search.size,
      } as any

    if(tree.typeId) {
      params.typeId = tree.typeId
    }
    request.sendRequest({
      address: 'warehouse/good/getGoodList',
      params,
      success: (resp: RespData) => {
        if(resp.code !== 0) return ElMessage.error(resp.msg || '获取物品管理列表失败')
        data.value = resp.data.records
        search.total = resp.data.total
        search.current = resp.data.current

        search.loading = false
      },
      fail: (resp: RespData) => {
        if(resp.code !== 0) return ElMessage.error(resp.msg || '获取物品管理列表失败')
        search.loading = false
      },
      method: "POST",
    })
  }
    req()

    const defaultProps = {
      children: 'children',
      label: 'name',
      isLeaf: 'leaf'
    }
    const getTreeList = () => {
      request.sendRequest({
        address: 'warehouse/good/getTypeTree',
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取收费项目分类树形图失败')
          console.log(resp.data)
          tree.treeData = resp.data
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取收费项目分类树形图失败')
          
        },
        method: "GET",
      })
    }
    getTreeList()

    const areaTreeRef = ref(null)
    const isNodeActive = ref()
    const orderNum = ref()
    const parentId = ref()
    const handleNode = (data: any) => {
      console.log(data, data.id)

      isNodeActive.value = data.id
      tree.typeId = data.id
      orderNum.value = data.orderNum
      parentId.value = data.superId

      req()

      menuVisbile.value = false

    }

    const tipsOPerRef = ref<HTMLElement | null>(null)
    const menuVisbile = ref(false)
    // 点击某一节点右击事件
    const handleNodeMenu = (e: MouseEvent, obj: any, node: any) => {

      nameType.value = obj.name
      tree.typeId = obj.id
      orderNum.value = obj.orderNum
      parentId.value = obj.superId

      menuVisbile.value = true
      // 获取鼠标右击的 x, y 坐标
      let x = e.clientX;
      let y = e.clientY;
      (tipsOPerRef.value as HTMLElement).style.top = y + 10 +  'px';
      (tipsOPerRef.value as HTMLElement).style.left = x + 20 + 'px';

    }

    const loadNode = (node:any, resolve: Function) => {
      console.log(node, resolve)
    }

    const titleType = ref('添加物品分类')
    const nameType = ref()
    const dialogVisible = ref(false)
    const itemType = ref()
    const modelOptions = ref([] as Option[])

    const getModelOptions = () => {
      request.sendRequest({
          address: `warehouse/getGoodsTypeSelect`,
          params: {},
          success: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error('获取类型' + resp.msg)
            modelOptions.value = resp.data
          },
          fail: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error('获取类型' + resp.msg)
          },
          method: "GET",
        })
    }
    getModelOptions()

    const closeDialog = () => {
      dialogVisible.value = false
    }
    const dialogBtnData = [
      {
        name: '取消',
				func: (data:object) => {
					console.debug('取消',JSON.parse(JSON.stringify(data)))
          dialogVisible.value = false
				}
      },
      {
        name: '保存',
        func: (data:object) => {
					console.debug('保存',JSON.parse(JSON.stringify(data)))
            if(titleType.value === '添加物品分类') {
              // if(itemType.value) {
                addGoodTypeTree()
              // } else {
              //   ElMessage.warning('请选择分类类型')
              // }
              
            }
            if(titleType.value === '修改物品分类') {
              editGoodTypeTree()
            }
            
				}
      }
    ]
    // 打开 添加物品分类
    const addGoodType = () => {
      titleType.value = '添加物品分类'
      nameType.value = ''
      dialogVisible.value = true
      console.log('点击了物品分类')
    }
    // 添加物品分类
    const addGoodTypeTree = () => {
      request.sendRequest({
        address: `warehouse/good/addType`,
        params: {
          name: nameType.value,
          itemType: itemType.value,
          superId: tree.typeId
        },
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error('添加物品类型' + resp.msg)
          tree.typeId = ''
          closeDialog()
          req()
          getTreeList()
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error('添加物品类型' + resp.msg)
        },
        method: "POST",
      })
    }

    // 打开 修改物品分类
    const edit = () => {
      titleType.value = '修改物品分类'
      dialogVisible.value = true
      
      // console.log(node, data, '点击了修改')
    }
    // 修改物品分类
    const editGoodTypeTree = () => {
      request.sendRequest({
        address: 'warehouse/good/updateType',
        params: {
          name: nameType.value,
          superId: parentId.value,
          id: tree.typeId,
          orderNum: orderNum.value
        },
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error('修改物品分类' + resp.msg)
          ElMessage.success('修改物品分类' + resp.msg)
          tree.typeId = ''
          menuVisbile.value = false
          closeDialog()
          req()
          getTreeList()
          console.log(resp.data)
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error('修改物品分类' + resp.msg)
          
        },
        method: "POST",
      })
    }
    // 删除大项
    const remove = () => {
      console.log('点击了删除')

      ElMessageBox.confirm(`此操作将永久删除【${nameType.value}】, 是否继续?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            request.sendRequest({
              address: `warehouse/good/delType/${tree.typeId}`,
              params: {},
              success: (resp: RespData) => {
                if(resp.code !== 0) return ElMessage.error(resp.msg || '删除失败')
                tree.typeId = ''
                menuVisbile.value = false
                ElMessage.success('删除成功')
                getTreeList()
              },
              fail: (resp: RespData) => {
                if(resp.code !== 0) return ElMessage.error(resp.msg || '删除失败')
              },
              method: "POST",
            })
          }).catch(() => {
            ElMessage({
              type: 'info',
              message: '已取消删除',
            });
          })
        
      }
    


    /** 抽屉部分开始 */
    const showWidget = useShowWidget;
    let showDrawer = ref(false)
    let showEditDrawer = ref(false)

    const handleClickDrawer = () => {
      groupDataAdd.value.forEach(i => i.value = '')
      if(tree.typeId === '') {
        showDrawer.value = false
        // 提示
        ElMessage.warning('请选择物品类目, 在点击新增')
      } else {
        showDrawer.value = true
      }
      
    }

    const drawerClose = (type:string) => {
      tree.typeId = ''

      ElMessageBox.confirm('此操作将关闭窗口, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {

				if(type === 'add') {
        showDrawer.value = false
        } else if (type === 'edit') {
          showEditDrawer.value = false
        }

			}).catch(() => {
					ElMessage({
						type: 'info',
						message: '已取消',
					});
      })
      
    }
    const cancel = (type:string) => {
      tree.typeId = ''
      if(type === 'add') {
        showDrawer.value = false
      } else if (type === 'edit') {
        showEditDrawer.value = false
      }
    }

    // 修改
    const handleEditItem = (rowData:any) => {
      showEditDrawer.value = true
      tree.typeId = rowData.typeId
      search.id = rowData.id
      groupDataUpdate.value.forEach((item: any) => {
          Object.keys(rowData).forEach(i => {
            if(item.name === i) {
            // console.log(data[item.name])
            item.value = rowData[item.name]
          }
        })
      })

      console.log(groupDataUpdate.value)
    }
    // 预警
    const handleWarning = (rowData:any) => {

    }
    // 删除
    const handleDelItem = (rowData: any) => {
      let id = rowData.id
      ElMessageBox.confirm('此操作将永久删除该项目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        request.sendRequest({
          address: `warehouse/good/del/${id}`,
          params: {},
          success: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error(resp.msg || '删除失败')
            ElMessage.success('删除成功')
            req()
          },
          fail: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error(resp.msg || '删除失败')
          },
          method: "POST",
        })
      }).catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消删除',
        });
      })
    }
  

    const save = (type:string) => {
      let params = {} as any 
      
      if(type === 'add') {
          groupDataAdd.value.forEach(item => {
            console.log(item)
            if(item.name === 'shelfLifeDay') {
              item.value = String(item.value).replace(/\D/g, '')
            }
            params[item.name] = item.value
          })
          params.typeId = tree.typeId

          request.sendRequest({
          address: 'warehouse/good/createGood',
          params,
          success: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error(resp.msg || '添加失败')
            ElMessage.success('添加成功')
            showDrawer.value = false
            
            req()
          },
          fail: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error(resp.msg || '添加失败')
          },
          method: "POST",
        })
      } else if (type === 'edit') {
        groupDataUpdate.value.forEach(item => {
            params[item.name] = item.value
            
        })

        console.log(groupDataUpdate.value)

        let result = groupDataUpdate.value.find(i => {
          return i.name === 'shelfLifeDay'
        })
        if(result?.value) {
          if(isNaN(Number(result.value))) {
                result.value = ''
                params.shelfLifeDay = ''
                ElMessage.warning('保质期不是数字哦')
            }
        }

        console.log(params)
        // params.typeId = tree.typeId
        params.id = search.id
        if(!params.itemName) {
          ElMessage.warning('名称不能为空哦')
          return false;
        } else {
            request.sendRequest({
              address: 'warehouse/good/updateGood',
              params,
              success: (resp: RespData) => {
                if(resp.code !== 0) return ElMessage.error(resp.msg || '修改失败')
                ElMessage.success('修改成功')
                req()
                showEditDrawer.value = false
              },
              fail: (resp: RespData) => {
                if(resp.code !== 0) {
                  return ElMessage.error(resp.msg)
                }
                
              },
              method: "POST",
            })
        }
      }

    }
    /** 抽屉部分结束 */
    return {
      ...toRefs(search),
      data,
      groupData,
      groupDataAdd,
      groupDataUpdate,

      handleEditItem,
      handleWarning,
      handleDelItem,

      handleCancelGood,
      handleRefresh,

      AddList,
      hanledSearch,
      onSubmit,
      handleCurrentChange,
      handleSizeChange,

      ...toRefs(tree),
      defaultProps,
      handleNode,

      tipsOPerRef,
      menuVisbile,
      handleNodeMenu,
      titleType,
      nameType,
      dialogVisible,
      isNodeActive,
      itemType,
      modelOptions,
      getModelOptions,
      closeDialog,
      dialogBtnData,
      addGoodType,
      edit,
      remove,
      orderNum,
      parentId,
      editGoodTypeTree,

      showDrawer,
      showEditDrawer,
      showWidget,
      handleClickDrawer,
      drawerClose,
      cancel,
      save,

      loadNode,
    }
  }
})
</script>

<style lang="scss" scoped>
.goods-main {
  width: 100%;
  height: 100%;
  background: white;
  .goods-head {
    height: 40px;
    line-height: 40px;
    text-align: right;
    padding-right: 20px;
  }
  .goods-content {
    display: flex;
    padding: 10px 20px;
    height: calc(100% - 50px);
    box-sizing: border-box;
    .left-area {
      background: white;
      box-shadow: 2px 2px 5px rgba(233, 230, 230 ,.8), -2px -2px 5px rgba(233, 230, 230 ,.8);
      border-radius: $radius-1;
      margin-right: 10px;
      position: relative;
      min-width: 240px;
      
      .area-search {
        padding-left: 5px;
        padding-top: 10px;
      }
      .area-tree {
        padding: 5px;
        height: calc(100% - 85px);
        overflow-y: auto;
        // margin-bottom: 45px;
        .all-goods {
          height: 32px;
          line-height: 32px;
          background: $a11-Color;
          color: white;
          padding-left: 10px;
          font-size: $fontSize-1;
        }
      }

      .area-btn-operation {
        position: absolute;
        left: 0;
        right: 0;
        bottom: 0;
        line-height: 35px;
        color: $mainColor;
        font-size: 14px;
        cursor: pointer;
        text-align: center;
        box-shadow: 1px 0 3px #ccc;
        user-select: none;
        background-color: white;

        & > span {
          padding: 5px 10px;
        }
      }

    }
    .right-area {
      width: calc(100% - 240px);
      background: white;
      box-shadow: 2px 2px 5px rgba(233, 230, 230 ,.8), -2px -2px 5px rgba(233, 230, 230 ,.8);
      border-radius: $radius-1;
      padding: 10px;
      padding-top: 20px;
      .table {
        height: calc(100% - 120px);
        padding: 0 20px;
        overflow: auto;
      }
      .page {
        height: 40px;
        line-height: 40px;
        background: white;
        margin: 10px 20px 5px;
        text-align: right;
      }
    }
  }
}

.node-tree-title {
  background: white;
  font-size: $fontSize;
  color: $mainColor;
}
.opation {
  font-size: $fontSize;
  padding-left: 30px;
}
.node-isActive {
  background: white;
  color: $mainColor;
  box-shadow: 0 0 5px 2px rgba(17, 185, 208, .3);
  border-radius: 4px;
  padding: 2px 5px;
}


.tipsOperation {
  background: white;
  width: 100px;
  height: 80px;
  box-shadow: 0 2px 4px #ccc;
  border-radius: 4px;
  position: fixed;
  z-index: 99;

  .tip-item {
    line-height: 35px;
    // text-align: center;
    cursor: pointer;
    padding-left: 15px;

    & > span {
      font-size: 14px;
      padding-left: 5px;
    }
  }
  .tip-item:hover {
    background: #e9e9e9;
  }
}
</style>